package com.yibo.db.helper;

import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.yibo.support.helper.Assert;
import com.yibo.support.helper.JsonHelper;
import com.yibo.support.helper.ObjectHelper;
import com.yibo.support.pojo.YBFilter;

import java.lang.reflect.Field;
import java.util.List;
import java.util.stream.Collectors;

import static com.yibo.support.constant.MsgConstant.SEARCH_PRO_IS_ERROR;

public class BaseService {


    protected  <T>QueryFilter<T>  result(T data){
        return new QueryFilter<T>().initResult(data);
    }


    protected  int  pageSize(QueryFilter filter){
        return filter.getPageSize() <= 0 ? 10 : filter.getPageSize();
    }


    protected  int pageNum(QueryFilter filter){
        return filter.getPageNum() <= 0 ? 1 : filter.getPageNum();
    }


    /**
     * 校验查询条件
     *
     * @param filter  查询条件
     * @param clazz   查询实体类
     * @param <T>     实体类型
     */
    @SuppressWarnings("unchecked")
    protected <T>void checkQueryFilter(QueryFilter filter,Class<T> clazz){
        List<YBFilter> filterList = filter.getFilters();
        if(ObjectHelper.isEmpty(filterList)){
            return;
        }

        List<String> pros = filterList.stream().map(YBFilter::getPro).collect(Collectors.toList());
        Field[] fields =  clazz.getDeclaredFields();
        for(Field field : fields){
            String fieldName  = field.getName();
            Assert.notEmpty(SEARCH_PRO_IS_ERROR,!pros.contains(fieldName));
        }
    }

    /**
     * 过滤查询
     *
     * @param filter  过滤条件
     * @param baseMapper   查询接口
     * @param <T>   查询类型
     * @return   返回值
     */
    @SuppressWarnings("unchecked")
    protected  <T>List<T> query(QueryFilter filter, BaseMapper<T> baseMapper){
        List<YBFilter> filters = filter.getFilters();

        EntityWrapper<T> entityWrapper = new EntityWrapper<>();
        for(YBFilter ybFilter : filters){
            YBFilter.SqlCode code = ybFilter.getSqlCode();
            //转化成下划线
            String pro = JsonHelper.toUnderLineField(ybFilter.getPro());
            String value = ybFilter.getValue();
            if("eq".equals(code.name())){
                entityWrapper.eq(pro,value);
            }else if("like".equals(code.name())){
                entityWrapper.like(pro,value);
            }
        }
        return baseMapper.selectList(entityWrapper);
    }

}
